package com.yun.article.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.model.article.dtos.ApArticleDTO;
import com.heima.model.article.dtos.ArticleHomeDTO;
import com.heima.model.article.enums.ArticleConstants;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.article.pojos.ApArticleConfig;
import com.heima.model.article.pojos.ApArticleContent;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.yun.article.enums.SizeEnum;
import com.yun.article.mapper.ApArticleConfigMapper;
import com.yun.article.mapper.ApArticleContentMapper;
import com.yun.article.mapper.ApArticleMapper;
import com.yun.article.service.ApArticleService;
import io.seata.core.context.RootContext;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

/**
 * @author Excell
 * @description 针对表【ap_article(文章信息表，存储已发布的文章)】的数据库操作Service实现
 * @createDate 2025-07-18 14:47:29
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class ApArticleServiceImpl extends ServiceImpl<ApArticleMapper, ApArticle>
        implements ApArticleService {

    private final ApArticleMapper apArticleMapper;

    private final ApArticleContentMapper apArticleContentMapper;

    private final ApArticleConfigMapper apArticleConfigMapper;

    @Override
    public ResponseResult load(ArticleHomeDTO articleHomeDTO, Short status) {
        // 增加健壮性
        if (articleHomeDTO.getSize() < SizeEnum.MIN_SIZE.getSize() || articleHomeDTO.getSize() > SizeEnum.MAX_SIZE.getSize()
                || articleHomeDTO.getSize() == null) {
            articleHomeDTO.setSize(SizeEnum.DEFAULT_SIZE.getSize());
        }

        if (articleHomeDTO.getMaxBehotTime() == null) {
            articleHomeDTO.setMaxBehotTime(new Date());
        }

        if (articleHomeDTO.getMinBehotTime() == null) {
            articleHomeDTO.setMinBehotTime(new Date());
        }


        return ResponseResult.okResult(apArticleMapper.load(articleHomeDTO, status));
    }


    @Override
    @Transactional
    public ResponseResult insertArticle(ApArticleDTO apArticleDTO) {
        log.info("Seata全局事务id=================>{}", RootContext.getXID());
        int i = 1 / 0;

        if (apArticleDTO == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }

        // 1. 保存文章
        ApArticle apArticle = ApArticle.builder()
                .title(apArticleDTO.getTitle())
                .authorId(apArticleDTO.getAuthorId())
                .authorName(apArticleDTO.getAuthorName())
                .channelId(apArticleDTO.getChannelId())
                .channelName(apArticleDTO.getChannelName())
                .layout(apArticleDTO.getLayout())
                .images(apArticleDTO.getImages())
                .createdTime(new Date())
                .publishTime(new Date())
                .syncStatus(ArticleConstants.SYNC_STATUS_NOT_SYNCED)
                .origin(ArticleConstants.ORIGIN_SELF)
                .build();

        apArticleMapper.insert(apArticle);

        // 2. 保存文章内容
        ApArticleContent apArticleContent = ApArticleContent.builder()
                .articleId(apArticle.getId())
                .content(apArticleDTO.getContent())
                .build();

        apArticleContentMapper.insert(apArticleContent);

        // 3. 保存文章配置
        ApArticleConfig apArticleConfig = ApArticleConfig.builder()
                .articleId(apArticle.getId())
                .isComment(ArticleConstants.ALLOW_COMMENT)
                .isForward(ArticleConstants.ALLOW_FORWARD)
                .isDown(ArticleConstants.NOT_DOWN)
                .isDelete(ArticleConstants.NOT_DELETE)
                .build();

        apArticleConfigMapper.insert(apArticleConfig);


        // 4. 返回结果，带上文章id
        return ResponseResult.okResult(apArticle.getId());
    }

    /**
     * @description: 文章下架
     * @title: articleDown
     * @param: [articleId]
     */
    @Override
    public void articleDown(Long articleId) {
        // 1. 参数校验
        if (articleId == null) {
            return;
        }

        // 2. 查询文章配置
        ApArticleConfig config = apArticleConfigMapper.selectOne(
                new LambdaQueryWrapper<ApArticleConfig>()
                        .eq(ApArticleConfig::getArticleId, articleId)
        );

        if (config == null) {
            return;
        }

        // 3. 执行更新（取反）
        int newStatus = config.getIsDown() != null && config.getIsDown() == 1 ? 0 : 1;

        int rows = apArticleConfigMapper.update(
                null,
                new LambdaUpdateWrapper<ApArticleConfig>()
                        .eq(ApArticleConfig::getArticleId, articleId)
                        .set(ApArticleConfig::getIsDown, newStatus)
        );

        if (rows == 0) {
            return;
        }

        // 4. 返回动态提示
        String msg = newStatus == 1 ? "文章下架成功" : "文章上架成功";
    }


}




